<?php 
/**
 * 车辆管理类
 * @Author    紫梦
 * @DateTime  2017-11-03
 * @copyright 响响租车
 * @version   1.0
 * @UpdateTime 2017-11-10
 */
namespace app\index\controller;
use \think\Request;
use \think\Db;
use app\common\model\CarType;
use app\common\model\CarFile;
use app\common\model\CarAttribute;
use app\common\model\Brand;
use app\common\model\Cars as CarsModel;
use app\common\model\CarAttr;
use app\common\model\Agency;
use app\common\model\Company;
use app\common\model\Personal;
use app\common\request\ClientLai;
use app\common\request\Oss;
use app\common\controller\Execl;


class Cars extends Base
{
	/**
	 *车辆列表
	 */
	public function index()
	{

		$request = Request::instance();
		$post = $request->post();
		
		if($request->isAjax()){
			$datemin = $post['datemin']??'';
            $datemax = $post['datemax']??'';
            $seach = $post['search']??'';
			$relevance = $post['relevance']??'';
            $agency = $post['agency_id']??'';
            $brand = $post['brand_id']??'';

	        if( !empty($datemin) && !empty($datemax) ){
	            $where['create_time'] = ['between time',[$datemin,$datemax]];	               
	                
	        }
	        if ( empty($datemin) && !empty($datemax) ){	            
                $where['create_time'] =['<= time',$datemax];
                	
                	
	        }
	        if ( !empty($datemin) && empty($datemax) ) {
	        	$where ['create_time'] = ['> time',$datemin];
	             
	        }
	        if ( !empty($seach) ) {
	        	$where['car_sn|car_unique_id|cardcode|equipment_id'] = ['like','%'.$seach.'%'];
	                
	        }
	        if ( !empty($relevance) ) {
	        	$where['relevance'] = $relevance;     
	                
	        }
	        if ( !empty($agency) ) {
	        	$where ['agency_id'] = $agency;
	                
	        }
	        if ( !empty($brand) ) {
	        	$where ['brand_id'] = $brand;
	                
	        }
	        
	        if( empty($where) ){
	        	$where = '1=1';
	        }        
            $model= CarsModel::where($where)
                            ->order('car_id', 'desc')
                            ->field('car_id,car_sn,	agency_id,car_unique_id,relevance,brand_id,holder_type,holder_id,create_time,band_status')
                            ->paginate($post['length'],false,[
                                    'type'     => 'bootstrap',
                                    'var_page' => 'page',
                                    'page'=>$post['start']/$post['length'] +1 ,
                                ]);


            if(count($model)>=1){

                foreach ($model as $key => $value) {
                	$value['brand_name'] = $value->brand_name;	
                	$value['agency_name'] = $value->agency_name;
                    $res['data'][] = $value;
                }
                
                $res['recordsTotal'] = $res['recordsFiltered'] = $model->total();
            }else{
                    $res['data']= '';
                    $res['recordsTotal'] = $res['recordsFiltered'] =0;
            }
            
            return $res;

		}else{
			
			$model = CarsModel::count();
			$this->assign('number',$model);
			$brand = Brand::all();
			$agency = Agency::all();
			$this->assign('brand',$brand);
			$this->assign('agency',$agency);
			$this->assign('brand_id',$post['brand_id']??null);	
			$this->assign('agency_id',$post['agency_id']??null);	
			$this->assign('relevance',$post['relevance']??null);	
			$this->assign('search_value',$post['search']??null);	
			$this->assign('datemin',$post['datemin']??null);	
			$this->assign('datemax',$post['datemax']??null);	
			return $this->fetch();
		}
	}

	/**
	 * 车辆基础数据导入
	 */
	public function excelToData()
	{
		$request = Request::instance();
		if($request->isPost()){
			$file = $request->file('excel');
			if($file){
				$info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
                if($info){
                    // 成功上传后 获取上传信息
                    $url = $info->getSaveName();
                    $ext = $info->getExtension();
                    $path = ROOT_PATH . 'public' . DS . 'uploads/'.$url;
					$excel = new Execl;
					$excelData = $excel->readerBase($path);
					
					if(empty($excelData)){
						$this->error('数据格式不合法');
					}
					$updateNum = 0;
					$insertNum = 0;
					// 遍历数据加入到数据库中去 
					foreach ($excelData as $key => $value) {
						if($key==0){
							continue;
						}
						// 查看库中是否有数据
						$car_id = Db::name('cars')->where(['car_unique_id' => $value[1]])->find();
						
						$carsData['car_sn'] = $value[0]??'';
						$carsData['car_unique_id'] = trim($value[1])??'';
						$carsData['motor_id'] = $value[2]??'';
						$carsData['car_name'] = $value[3]??'';
						$bandName['name'] = $value[4]??'';
						$carsData['brand_id'] = Db::name('brand')->where($bandName)->value('id');

						$carsData['supplier_no'] = $value[6]??'';
						switch ($carsData['supplier_no']) {
							case '博鹭途':
								
								$carsData['supplier_no'] = 1376920002;
								break;
							case '唯特迅':
								
								$carsData['back_supplier_no'] = 1376920001;
								break;	
							default:
								$carsData['supplier_no'] = null;
								break;
						}

						$carsData['sim_id'] = $value[7]??'';
						$carsData['cardcode'] = $value[8]??'';
						$carsData['equipment_id'] = $value[9]??null;
						$carsData['back_supplier_no'] = $value[10]??'';
						switch ($carsData['back_supplier_no']) {
							case '博鹭途':
								
								$carsData['back_supplier_no'] = 1376920002;
								break;
							case '唯特迅':
								
								$carsData['back_supplier_no'] = 1376920001;
								break;		
							default:
								$carsData['back_supplier_no'] = null;
								break;
						}

						$carsData['back_sim_id'] = $value[11]??'';
						$carsData['back_cardcode'] = $value[12]??'';
						$carsData['back_equipment_id'] = $value[13]??null;
						$carsData['relevance'] = $value[14]??'';
						switch ($carsData['relevance']) {
							case '分时租赁':
								
								$carsData['relevance'] = 1;
								break;
							case '企业用车':
								
								$carsData['relevance'] = 2;
								break;
							case '共享用车':
								
								$carsData['relevance'] = 3;
								break;
							case '长租车辆':
								
								$carsData['relevance'] = 4;
								break;
							case '自测试用':
								
								$carsData['relevance'] = 5;
								break;
							case '上牌整备':
								
								$carsData['relevance'] = 6;
								break;
							case '整备待租':
								
								$carsData['relevance'] = 7;
								break;	
							default:
								$carsData['relevance'] = null;
								break;
						}
						$agencyName['name'] = $value[16]??'';
						$carsData['agency_id'] =  Db::name('agency')->where($agencyName)->value('id');

						$newArr = array_filter($carsData);

						switch ($value[5]) {
							case '小型轿车':
								
								$newArr['car_breed'] = 0;
								break;
							case 'SUV':
								
								$newArr['car_breed'] = 1;
								break;
							case '中巴':
								
								$newArr['car_breed'] = 2;
								break;	
							default:
								$newArr['car_breed'] = 0;
								break;
						}
						$companyName['name'] = $value[15]??'';
						$company = Db::name('company')->where($companyName)->value('id');
						if($company){
							$newArr['holder_type'] = 0;
							$newArr['holder_id'] = $company;
						}
						
						if($car_id && !empty($newArr['car_unique_id'])){
							
							$newArr['update_time'] = time();
							$res = Db::name('cars')->where('car_id',$car_id['car_id'])->update($newArr);
							$updateNum++;
						}elseif(!empty($newArr['car_unique_id'])){
							$newArr['create_time'] = time();
							$newArr['update_time'] = time();
							$res = Db::name('cars')->insert($newArr);
							$insertNum++;					
						}
					}

					$resArr = ['status'=>0,'msg' =>'更新'.$updateNum.'条,插入'.$insertNum.'条'];
					return $resArr;
                }else{
					$this->error($file->getError());
                }
			}else{
				$this->error('没有上传文件');
			}
		}else{
			return $this->fetch('excel_to_data');
		}
	}

	/**
	 * 车辆基础数据模板
	 */
	public function carExcel()
	{
		
		$brand = Brand::all();
		$company = Company::all();
		$agency = Agency::all();
		$excel = new Execl;

		$excel->carExcel($brand,$company,$agency);
					

	}


	/**
	 * 绑定车辆
	 */
	public function bandCars($id)
	{
		$config = config('blt_lai');
		$obj = new ClientLai($config['user_name'],$config['password']);
		$model = CarsModel::get($id);
		$data['supplier_no'] = $model['supplier_no'];
		$data['car_unique_id'] = $model['car_unique_id'];
		$data['equipment_id'] = $model['equipment_id'];
		$data['bluetooth_id'] = ltrim($model['equipment_id'],0);
		$data['license_plate'] = $model['car_sn'];
		
		$res = $obj->request_post(rtrim($config['url'],'/').'/bind_car',$data);

		$arr = json_decode($res,true);


		if($arr['result']==0){			
			try{
				$model->band_status = 1;
				$model->save();
			    
			}catch(\Exception $e){
				$arr['result'] = 1;
			    $arr['msg'] = '绑定成功,但是数据库状态更新失败';
			}

		}
		return $arr;
		
	}

	/**
	 * 解绑车辆
	 */
	public function unBandCars($id)
	{

		$config = config('blt_lai');
		$obj = new ClientLai($config['user_name'],$config['password']);
		$model = CarsModel::get($id);
		$data['supplier_no'] = $model['supplier_no'];
		$data['car_unique_id'] = $model['car_unique_id'];
		
		$res = $obj->request_post(rtrim($config['url'],'/').'/unbind_car',$data);

		$arr = json_decode($res,true);


		if($arr['result']==0){			
			try{
				$model->band_status = 0;
				$model->save();
			    
			}catch(\Exception $e){
				$arr['result'] = 1;
			    $arr['msg'] = '解绑成功,但是数据库状态更新失败';
			}

		}
		return $arr;
	}

	/**
	 * 删除车辆图片
	 */
	public function carsImgDel($id)
	{
		$msg['status'] = 0;
		$url = CarFile::get($id);
		$oss = new Oss();
		$res = false;
		if($oss->unlinkOss($url['file_url'])){
			$res = CarFile::destroy($id);
			
		}
		if(!$res) {$msg['status'] = 1; $msg['msg'] = '删除失败,请稍后再试';}
		
		return $msg;
	}

	/**
	 * 删除车辆
	 */
	public function delete($id)
	{
		$msg['status'] = 0;
		$data = CarsModel::get($id);
		if($data['band_status'] == 1){
			$msg['status'] = 1; 
			$msg['msg'] = '删除失败,请解除绑定';
			return $msg;
		}
		$res = CarsModel::destroy($id);
		if(!$res) {
			$msg['status'] = 1; 
			$msg['msg'] = '删除失败,请稍后再试';

		}
		
		return $msg;
	}

	/**
	 * 编辑车辆
	 */
	public function edit($car_id=1)
	{
		$request = Request::instance();

		if($request->isPost()){
			
			// dump($_POST);

			$data = $request->post();
			// 商品基础信息添加
			$model = new CarsModel();
		
			$result = $model->allowField(true)->validate(true)->save($data,['car_id' => $data['car_id']]);
			if(false === $result){
			    // 验证失败 输出错误信息
			    $this->error($model->getError());
			}
			$car_id = $data['car_id'];

			//电子文件
			$travel_image = $request->file('travel_image');
			$register_image = $request->file('register_image');
			$image = $request->file('image');
			if($travel_image || $register_image || $image){
				$oss = new Oss();
			}
			//添加行驶证
			if($travel_image){
				foreach ($travel_image as $key => $value) {
					$url = $oss->uploadOss($value);
					
					if($url){
						Db::name('car_file')->insert(['car_id'=>$car_id,'file_url'=>$url,'file_type'=>0]);
					}
				}
			}

			//添加登记证
			if($register_image){
				foreach ($register_image as $key => $value) {
					$url = $oss->uploadOss($value);
					
					if($url){
						Db::name('car_file')->insert(['car_id'=>$car_id,'file_url'=>$url,'file_type'=>1]);
					}
				}
			}
			//其它电子文件的添加 joy_car_images car_id,image_url,image_type=2
			if($image){
				foreach ($image as $key => $value) {
					$url = $oss->uploadOss($value);
					
					if($url){
						Db::name('car_file')->insert(['car_id'=>$car_id,'file_url'=>$url,'file_type'=>2]);
					}
				}
			}

			//车辆属性的添加 joy_car_attr car_id,attr_id,attr_value
			if(!empty($data['car_attr'])){
				
				$attrModel = new CarAttr();
				$carAttrArr = $data['car_attr'];


				foreach ($carAttrArr as $key => $value) {
					$attrData[] = ['car_id'=>$car_id,'attr_id'=>$key,'attr_value'=>$value];			
				}
				// 删除原来的数据
						
				CarAttr::destroy(['car_id' => $car_id]);
				$result = $attrModel->saveAll($attrData);

			}

			if($result){
	            $this->success('更新成功', 'index/Cars/index');
	        } else {
	            $this->error('更新失败');
	        }
	        
		}else{
			$brand = Brand::all();
			$type = Db::table('joy_car_type')->column('id,name');
			$data = CarsModel::get($car_id);
			
			//所有人
			$data['holder_id'] = $data->getData('holder_id');
			if($data['holder_type']==0){
				$holder = Db::table('joy_company')->column('id,name');
			}else{
				$holder = Db::table('joy_personal')->column('id,name');

			}

			// 图片
			$images = Db::name('car_file')->where(['car_id'=>$car_id])->order('file_type')->column('id,file_url,file_type');
			
			//车辆属性
			$carAttribute = CarAttribute::all(['type_id'=>$data['car_type']]);
			foreach ($carAttribute as $key => $value) {
				$attr_value = Db::name('car_attr')
								->where(['car_id'=>$car_id,'attr_id'=>$value['attr_id']])
								->column('attr_value');
				$carAttribute[$key]['attr_value'] = $attr_value[0];
				
			}
			//经销商
			$agency = Agency::all();

			$this->assign('brand',$brand);
			$this->assign('holder',$holder);
			$this->assign('type',$type);
			$this->assign('data',$data);
			$this->assign('images',$images);
			$this->assign('carAttribute',$carAttribute);
			$this->assign('agency_id',$agency);

			return $this->fetch();

		}
	}

	/**
	 *添加车辆
	 */
	public function add()
	{
		$request = Request::instance();

		if($request->isPost()){

			$data = $request->post();

			//基础信息添加
			$model = new CarsModel();
			
			$result = $model->validate(true)->allowField(true)->save($data);
			if(false === $result){
			    // 验证失败 输出错误信息
			    $this->error($model->getError());
			}

			$car_id = $model->car_id;

			//电子文件
			$travel_image = $request->file('travel_image');
			$register_image = $request->file('register_image');
			$image = $request->file('image');
			if($travel_image || $register_image || $image){
				$oss = new Oss();
			}
			//添加行驶证
			if($travel_image){
				foreach ($travel_image as $key => $value) {
					$url = $oss->uploadOss($value);
					
					if($url){
						Db::name('car_file')->insert(['car_id'=>$car_id,'file_url'=>$url,'file_type'=>0]);
					}
				}
			}

			//添加登记证
			if($register_image){
				foreach ($register_image as $key => $value) {
					$url = $oss->uploadOss($value);
					
					if($url){
						Db::name('car_file')->insert(['car_id'=>$car_id,'file_url'=>$url,'file_type'=>1]);
					}
				}
			}
			//其它电子文件的添加 joy_car_images car_id,image_url,image_type=2
			if($image){
				foreach ($image as $key => $value) {
					$url = $oss->uploadOss($value);
					
					if($url){
						Db::name('car_file')->insert(['car_id'=>$car_id,'file_url'=>$url,'file_type'=>2]);
					}
				}
			}

			//车辆属性的添加 joy_car_attr car_id,attr_id,attr_value
			if(!empty($data['car_attr'])){
				$attrModel = new CarAttr();
				$carAttrArr = $data['car_attr'];

				foreach ($carAttrArr as $key => $value) {
					if(!empty($value)){
						$attrData[] = ['car_id'=>$car_id,'attr_id'=>$key,'attr_value'=>$value];			
					}
				}			
				$result = $attrModel->saveAll($attrData);

			}

			if($result){
	            $this->success('新增成功', 'Cars/index');
	        } else {
	            $this->error('新增失败');
	        }

			


		}else{
			$brand = Brand::All();
			$holder = Company::scope('status')->column('id,name');
			$type = Db::table('joy_car_type')->column('id,name');
			$agency = Agency::column('id,name');
			// dump($brand);
			$this->assign('brand',$brand);
			$this->assign('holder',$holder);
			$this->assign('type',$type);
			$this->assign('agency',$agency);
			return $this->fetch();

		}
	}
	
	/**
	 * 模型列表
	 */
	public function typeList()
	{
	    $carsTypeList = CarType::all();                
	    // $carsTypeList = $model->order("id desc")->paginate(10);

	    $this->assign('carsTypeList',$carsTypeList);
	    return $this->fetch('type_list');

	}

	/**
	 * 删除模型
	 */
	public function typeDel($id)
	{
		//需要删除模型下所有属性
		$msg['status'] = 0;
		
		$res = CarType::destroy($id);
		if(!$res) {
			$msg['status'] = 1; $msg['msg'] = '删除失败,请稍后再试';

			return $msg;
		}
		
		if(CarAttribute::get(['type_id'=>$id])){
			$res = CarAttribute::destroy(['type_id'=>$id]);
			if(!$res) {$msg['status'] = 1; $msg['msg'] = '删除失败,请稍后再试';}
			
		}
		
		return $msg;



	}

	/**
	 * 添加模型
	 */
	public function typeAdd()
	{
		$request = Request::instance();


		if($request->isAjax())
		{
			// $msg['status'] = 1;
			// 		$msg['msg'] = 2;
					
			// 		return json($msg);die;
			$msg['status'] = 0;
			$data = $request->post();

			$model = new CarType();

			$model->data($data);
			$res = $model->allowField(true)->save();

			if($res){

				$msg['msg'] = '添加成功';
				
			}else{

			    $msg['status'] = 1;
				$msg['msg'] = '添加失败,请稍后再试';
			}

			return $msg;
					
		}else{

	    	return $this->fetch('type_add');		
		}
	}

	/**
	 * 模型编辑
	 */
	public function typeEdit()
	{
		$request = Request::instance();


		if($request->isAjax())
		{
			$msg['status'] = 0;
			$data = $request->post();

			$model = new CarType();

			
			$res = $model->update($data);

			if($res){

				$msg['msg'] = '更新成功';
				
			}else{

			    $msg['status'] = 1;
				$msg['msg'] = '更新失败,请稍后再试';
			}

			return $msg;
					
		}else{

			$id = $request->get('id');	
			$data = Db::table('joy_car_type')->where(['id'=>$id])->find();
			
			$this->assign('data',$data);

			return $this->fetch('type_edit');
		}

	}

	/**
	 * 属性列表
	 */
	public function attrList()
	{
		$model = new CarAttribute();
		$data = $model->select();

		$this->assign('writer',['手工录入','多行文本','列表选择']);
		$this->assign('data',$data);
		return $this->fetch('attr_list');
	}

	/**
	 * 删除属性
	 */
	public function attrDel($id)
	{
		$msg['status'] = 0;
		
		$res = CarAttribute::destroy($id);
		if(!$res) {$msg['status'] = 1; $msg['msg'] = '删除失败,请稍后再试';}
		
		return $msg;
	}

	/**
	 * 编辑属性
	 */
	public function attrEdit($attr_id)
	{
		$request = Request::instance();


		if($request->isAjax())
		{
			$msg['status'] = 0;
			$data = $request->post();

			$model = new CarAttribute();

			
			$res = $model->update($data);

			if($res){

				$msg['msg'] = '更新成功';
				
			}else{

			    $msg['status'] = 1;
				$msg['msg'] = '更新失败,请稍后再试';
			}

			return $msg;
					
		}else{

			
			$data = Db::name('car_attribute')->where(['attr_id'=>$attr_id])->find();
			// 查询模型
			$type = Db::table('joy_car_type')->column('id,name');
			// dump($type);
			$this->assign('type',$type);

			$this->assign('data',$data);

			return $this->fetch('attr_edit');
		}
	}

	/**
	 * 添加属性
	 */
	public function attrAdd()
	{
		$request = Request::instance();

		if($request->isAjax())
		{
			$msg['status'] = 0;
			
			$data = $request->post();
			$data['attr_values'] = trim($data['attr_values']);
			$model = new CarAttribute;
			$model->data($data);

			$res = $model->allowField(true)->save();

			if($res){

				$msg['msg'] = '添加成功';
				
			}else{

			    $msg['status'] = 1;
				$msg['msg'] = $res;
			}

			return $msg;
		}
		else
		{
			// 查询模型
			$type = Db::table('joy_car_type')->column('id,name');
			// dump($type);
			$this->assign('type',$type);

			return $this->fetch('attr_add');
			
		}
	}

	/**
	 * ajax获取共享车主
	 */
	public function ajaxGetHolder($type)
	{
		if($type == 1){
			return Personal::column('id,name');
		}elseif($type ==="0"){
			return Company::scope('status')->column('id,name');

		}else{
			return ['请选择'];
		}

	}

	/**
	 * ajax获取模板属性
	 */
	public function ajaxGetType($type = 1)
	{

		$data = CarAttribute::all(['type_id'=>$type]);
		// $data = $model->toArray(); // 

		return $data;

	}


}